package com.java.dao.impl;

import com.java.jdbcUtils.utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author xyd
 * @Date 2021/12/6 13:37
 * @Version 1.0
 */
public abstract class baseDao {

    private QueryRunner queryRunner = new QueryRunner();

    public int update(String sql,Object ... args){
        Connection conn = utils.getConnection();

        try {
            return queryRunner.update(conn,sql,args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            utils.closeConn(conn);
        }
        return -1;
    }

    //查询一个对象
    public <T> T queryForOne(Class<T> type,String sql,Object ... args){
        Connection conn = utils.getConnection();
        try {
            return queryRunner.query(conn,sql,new BeanHandler<T>(type),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            utils.closeConn(conn);
        }
        return null;
    }

    //查询多个
    public <T>List<T> queryForList(Class<T> type,String sql,Object ... args){
        Connection conn = utils.getConnection();
        try {
            return queryRunner.query(conn,sql,new BeanListHandler<T>(type),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            utils.closeConn(conn);
        }
        return null;
    }

    //查询单个
    public Object queryForSingleValue(String sql,Object ... args){
        Connection conn = utils.getConnection();
        try {
            return queryRunner.query(conn,sql,new ScalarHandler(),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            utils.closeConn(conn);
        }
        return null;
    }
}
